<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="账户名称">
                <a-input v-model="queryParam.name" placeholder="请输入账户名称"/>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="账户状态">
                <a-select v-model="queryParam.status" placeholder="请选择" default-value="0">
                  <a-select-option :value="0">正常</a-select-option>
                  <a-select-option :value="1">禁用</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
      
            <a-col :md="8" :sm="24">
              <span class="table-page-search-submitButtons"">
                <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button style="margin-left: 8px" @click="() => this.queryParam = {}">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <div class="table-operator">
        <a-button type="primary" icon="plus" @click="handleAdd">新建</a-button>
		<a-button v-if="selectedRowKeys.length > 0" type="danger" icon="delete" @click="handleDelete(selectedRows)">删除</a-button>
      </div>

      <s-table
        ref="table"
        size="default"
        rowKey="key"
        :columns="columns"
        :data="loadData"
        :alert="true"
        :rowSelection="rowSelection"
        showPagination="auto"
      >
        <span slot="primary" slot-scope="text, record, index">
          {{ record.id}}
        </span>
        <span slot="status" slot-scope="text">
          <a-badge :status="text | statusTypeFilter" :text="text | statusFilter" />
        </span>
		<span slot="role" slot-scope="text, record">
			<a-tag color="#87d068">
			  {{record?.role ? record.role.name : "" }}
			</a-tag>
		</span>
        <span slot="description" slot-scope="text">
          <ellipsis :length="10" tooltip>{{ text }}</ellipsis>
        </span>
		<span slot="time" slot-scope="text">
		  {{ text | dateTimeFilter}}
		</span>
		
        <span slot="action" slot-scope="text, record">
          <template>
            <a @click="handleEdit(record)">编辑</a>
            <a-divider type="vertical" />
						<a @click="handleRole(record)">分配角色</a>
						<a-divider type="vertical" />
            <a @click="handleDelete(record)">删除</a>
          </template>
        </span>
      </s-table>

      <create-form
        ref="createModal"
        :visible="visible"
        :loading="confirmLoading"
        :model="mdl"
        @cancel="handleCancel"
        @ok="handleOk"
      />
	  
	  <role-form
	    ref="roleModal"
	    :visible="roleVisible"
	    :loading="confirmLoading"
	    :model="mdl"
	    @cancel="handleRoleCancel"
	    @ok="handleRoleOk"
	  />
	  
    </a-card>
  </page-header-wrapper>
</template>

<script>
import moment from 'moment'
import { STable, Ellipsis } from '@/components'
import { page, edit, deleteAll } from '@/api/account'
import CreateForm from './modules/CreateForm'
import RoleForm from './modules/RoleForm'

const columns = [
  {
    title: 'ID',
    scopedSlots: { customRender: 'primary' }
  },
  {
    title: '账户名',
    dataIndex: 'name'
  },
  {
    title: '描述',
    dataIndex: 'desp',
    scopedSlots: { customRender: 'description' }
  },
  {
    title: '状态',
    dataIndex: 'status',
    scopedSlots: { customRender: 'status' }
  },
  {
    title: '角色',
    scopedSlots: { customRender: 'role' }
  },
  {
    title: '更新时间',
    dataIndex: 'updateTime',
	scopedSlots: { customRender: 'time' }
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '200px',
    scopedSlots: { customRender: 'action' }
  }
]

const statusMap = {
  0: {
    status: 'success',
    text: '正常'
  },
  // 1: {
  //   status: 'processing',
  //   text: '运行中'
  // },
  // 2: {
  //   status: 'success',
  //   text: '已上线'
  // },
  1: {
    status: 'error',
    text: '禁用'
  }
}

export default {
  name: 'Account',
  components: {
    STable,
    Ellipsis,
    CreateForm,
	RoleForm
  },
  data () {
    this.columns = columns
    return {
      // create model
      visible: false,
	  roleVisible: false,
      confirmLoading: false,
      mdl: null,
      // 查询参数
      queryParam: {},
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const requestParameters = Object.assign({}, parameter, {parameter:this.queryParam})
        console.log('loadData request parameters:', requestParameters)
        return page(requestParameters)
          .then(res => {
            return res.data
          })
      },
      selectedRowKeys: [],
      selectedRows: []
    }
  },
  filters: {
    statusFilter (type) {
      return statusMap[type].text
    },
    statusTypeFilter (type) {
      return statusMap[type].status
    },
	dateTimeFilter(time){
		return moment(time).format('YYYY-MM-DD HH:mm:ss')
	}
  },
  computed: {
    rowSelection () {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },
  methods: {
    handleAdd () {
      this.mdl = null
      this.visible = true
    },
    handleEdit (record) {
      this.visible = true
      this.mdl = { ...record }
    },
	handleRole(record){
		this.roleVisible = true
		this.mdl = { ...record }
	},
	handleDelete(record){
		const ids = []
		if (record &&　Array.isArray(record)){
			record.forEach(item => {
				ids.push(item.id)
			})
		}else{
			ids.push(record.id)
		}
		deleteAll(ids).then(res => {
			  if(res.code == 200){
				  // 刷新表格
				  this.$refs.table.refresh(true)
				  this.$message.info('删除成功')
			  }else{
				  this.$message.error('删除失败')
			  }
		  }).finally(()=>{
			  this.confirmLoading = false
			  this.selectedRowKeys.length = 0
			  this.selectedRows.length = 0
		  })
	},
    handleOk () {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          console.log('values', values)
		  edit(values).then(res => {
			  if(res.code == 200){
				  // 重置表单数据
				  form.resetFields()
				  // 刷新表格
				  this.$refs.table.refresh(true)
				  this.$message.info('修改成功')
				  this.visible = false
			  }else{
				  this.$message.error('修改失败')
			  }
		  }).finally(()=>{
			  this.confirmLoading = false
		  })
        } else {
          this.confirmLoading = false
        }
      })
    },
	handleRoleOk(){
		const form = this.$refs.roleModal.form
		this.confirmLoading = true
		form.validateFields((errors, values) => {
		  if (!errors) {
		    console.log('values', values)
		edit(values).then(res => {
		  if(res.code == 200){
			  // 重置表单数据
			  form.resetFields()
			  // 刷新表格
			  this.$refs.table.refresh(true)
			  this.$message.info('分配角色成功')
			  this.roleVisible = false
		  }else{
			  this.$message.error('分配角色失败')
		  }
		}).finally(()=>{
		  this.confirmLoading = false
		})
		  } else {
		    this.confirmLoading = false
		  }
		})
	},
    handleCancel () {
      this.visible = false
      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
	handleRoleCancel () {
	  this.roleVisible = false
	  const form = this.$refs.roleModal.form
	  form.resetFields() // 清理表单数据（可不做）
	},
    handleSub (record) {
      if (record.status !== 0) {
        this.$message.info(`${record.no} 订阅成功`)
      } else {
        this.$message.error(`${record.no} 订阅失败，规则已关闭`)
      }
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    resetSearchForm () {
      this.queryParam = {
        date: moment(new Date())
      }
    }
  }
}
</script>
